<template>
  <el-form
    ref="formLogin"
    :model="loginData.loginForm"
    :rules="LoginRules"
    class="login-form"
    label-position="top"
    label-width="120px"
    size="large"
  >
    <el-row style="margin-right: -10px; margin-left: -10px">
      <el-col :span="24" class="input-row">
        <h2 class="form-title">{{ t('sys.login.signInFormTitle') }}</h2>
      </el-col>
      <!-- ====================debug代码======================== -->
      <div
        v-if="envState == 'true'"
        style="border: dashed 1px #fff; width: 100%; margin-bottom: 20px"
      >
        <el-tag type="warning"
          >仅用于于Debug!!运营管理系统->系统管理->租户管理->租户列表->租户编号</el-tag
        >
        <el-col :span="24" class="input-row">
          <el-input
            v-model="loginTenantId"
            placeholder="请输入租户ID，租户id由url中?tenantId=xxx获取！"
            link
            type="primary"
            @change="handleUpdateTenantId"
          />
        </el-col>
      </div>

      <!-- ====================debug 代码结束===================== -->
      <el-col :span="24" class="input-row">
        <el-input
          v-model="loginData.loginForm.username"
          :placeholder="t('login.usernamePlaceholder')"
        />
      </el-col>
      <el-col :span="24" class="input-row">
        <el-input
          v-model="loginData.loginForm.password"
          :placeholder="t('login.passwordPlaceholder')"
          show-password
          type="password"
          @keyup.enter="getCode()"
        />
      </el-col>
      <el-col :span="24" class="input-row text-btns">
        <label class="record-pwd">
          <el-checkbox v-model="loginData.loginForm.rememberMe" />
          <!-- <input v-model="loginData.loginForm.rememberMe" type="checkbox"/> -->
          <span>{{ t('login.remember') }}</span>
        </label>
        <span class="forget-pwd" @click="forgetPwdDialogVisible = true">{{
          t('login.forgetPassword')
        }}</span>
      </el-col>
      <el-col :span="24" class="input-row">
        <el-button
          :loading="loginLoading"
          round
          @click="getCode()"
          color="#ffffff"
          class="submit-btn"
          :class="{ active: canSubmit }"
        >
          {{ t('login.login') }}
        </el-button>
      </el-col>
    </el-row>
  </el-form>
  <!-- 滑动验证码模块 -->
  <Verify
    ref="verify"
    :captchaType="captchaType"
    :imgSize="{ width: '400px', height: '200px' }"
    mode="pop"
    @success="handleLogin"
  />
  <!-- 忘记密码 -->
  <el-dialog
    :title="t('forget.title')"
    v-model="forgetPwdDialogVisible"
    width="540px"
    :scroll="true"
    max-height="600px"
  >
    <PwdForget @destroy="forgetPwdDialogVisible = false" v-if="forgetPwdDialogVisible" />
  </el-dialog>
</template>
<script lang="ts" setup>
import { PwdForget } from '@/components/PwdForget'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
defineOptions({ name: 'LoginForm' })

const { t } = useI18n()

const formLogin = ref()

const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()
const redirect = ref<string>('')
const loginLoading = ref(false)
const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字
const forgetPwdDialogVisible = ref(false)

const canSubmit = computed<boolean>(() => {
  if (loginData.loginForm.password && loginData.loginForm.username) {
    return true
  } else {
    return false
  }
})
const LoginRules = {
  // tenantName: [required],
  username: [required],
  password: [required]
}
const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    // tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '',
    username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
    password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
    captchaVerification: '',
    rememberMe: false // 默认记录我。如果不需要，可手动修改
  }
})

// 获取验证码
const getCode = async () => {
  if (!canSubmit.value) {
    return
  }
  console.log('>>>> getCode', loginData)
  // 情况一，未开启：则直接登录
  if (loginData.captchaEnable === 'false') {
    await handleLogin({})
  } else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
    // 弹出验证码
    verify.value.show()
  }
}
// 获取租户 ID--已废弃，从url中获取
// const getTenantId = async () => {
//   if (loginData.tenantEnable === 'true') {
//     const res = await LoginApi.getTenantIdByName(loginData.loginForm.tenantName)
//     authUtil.setTenantId(res)
//   }
// }
// 记住我
const getLoginFormCache = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe
      // tenantName: loginForm.tenantName ? loginForm.tenantName : loginData.loginForm.tenantName
    }
  }
}
// 根据域名，获得租户信息--是否还需要？
const getTenantByWebsite = async () => {
  const website = location.host
  const res = await LoginApi.getTenantByWebsite(website)
  if (res) {
    // loginData.loginForm.tenantName = res.name
    authUtil.setTenantId(res.id)
  }
}
// 登录
const handleLogin = async (params) => {
  loginLoading.value = true
  try {
    loginData.loginForm.captchaVerification = params.captchaVerification
    const res = await LoginApi.login(loginData.loginForm)
    if (!res) {
      return
    }
    if (loginData.loginForm.rememberMe) {
      authUtil.setLoginForm({ ...loginData.loginForm })
    } else {
      authUtil.removeLoginForm()
    }
    authUtil.setToken(res)
    sessionStorage.setItem('userId', res.userId)
    if (!redirect.value) {
      redirect.value = '/'
    }
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      push({ path: redirect.value || permissionStore.addRouters[0].path })
    }
  } finally {
    loginLoading.value = false
    // loading.value.close()
  }
}
// ==================debug代码 start==================
// const envState = ref(import.meta.env.VITE_DEV)
const envState = ref(false)
authUtil.setTenantId('1')
const loginTenantId = ref(authUtil.getTenantId())
const handleUpdateTenantId = async () => {
  if (loginTenantId.value) {
    authUtil.setTenantId(loginTenantId.value)
  }
}
// ===================debug 代码 end=====================
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
onMounted(() => {
  getLoginFormCache()
  getTenantByWebsite()
})
</script>
<style lang="scss">
// 覆盖样式
.dark {
  .login-form {
    .el-input__icon {
      svg {
        color: #fff;
      }
    }
  }
}
.login-form {
  input:-webkit-autofill,
  textarea:-webkit-autofill,
  select:-webkit-autofill {
    background-image: none;
    -webkit-box-shadow: 0 0 0px 1000px transparent inset !important;
    background-color: transparent;
    transition: background-color 50000s ease-in-out 0s;
  }

  .el-input--large .el-input__inner {
    height: 42px;
  }

  .el-input__wrapper {
    box-shadow: 0 0 0 1px #fff inset;
    padding: 1px 20px;
  }

  .el-input__icon {
    width: 24px;
    height: 22px;
    svg {
      width: 100%;
      height: 100%;
    }
  }

  .anticon {
    &:hover {
      color: var(--el-color-primary) !important;
    }
  }
}
</style>

<style lang="scss" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.login-form {
  background: rgba(255, 255, 255, 0.08);
  box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.08);
  border: 1px solid #566567;
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 38px 28px;

  .form-title {
    font-weight: 400;
    font-size: 22px;
    color: #ffffff;
    line-height: 30px;
    text-align: center;
    width: 100%;
    margin-top: 0;
    margin-bottom: 28px;
  }

  .input-row {
    padding-right: 10px;
    padding-left: 10px;
    margin-bottom: 14px;

    &.text-btns {
      justify-content: space-between;
      align-items: center;
      display: flex;
      margin-bottom: 30px;
    }
  }

  .record-pwd {
    span {
      display: inline-block;
      margin-left: 10px;
      color: #ffffff;
    }
  }

  .text-btns .forget-pwd {
    cursor: pointer;
    font-weight: 500;
    color: #ffffff;
  }

  .submit-btn {
    transition: all 0.2s;
    width: 100%;
    opacity: 0.5;
    cursor: not-allowed;

    &.active {
      opacity: 1;
      cursor: pointer;
    }
  }

  .login-code {
    float: right;
    width: 100%;
    height: 38px;

    img {
      width: 100%;
      height: auto;
      max-width: 100px;
      vertical-align: middle;
      cursor: pointer;
    }
  }
}
</style>
